package com.gitee.feizns.explore.data_structure.linked_list.singly.remove_nth_from_end;

/**
 * 删除链表的倒数第N个节点
 *
 * 给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
 * @author feizns
 * @since 2019/9/30
 */
public class RemoveNthFromEnd {

    public static void main(String[] args) {
        ListNode node = create();
        removeNthFromEnd(node, 3).print();
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int i = 0;
        ListNode ret = head;
        ListNode prev = null;
        ListNode curt = head;

        while ( curt != null ) {
            if ( i == n )
                prev = prev == null ? head : prev.next;
            else
                i++;
            curt = curt.next;
        }

        if ( i == n ) {
            if ( prev == null )
                return head.next;
            else
                removeNext(prev);
        }

        return ret;

        //        int i = 0;
        //        ListNode ret = head;
        //        ListNode prev = null;
        //        ListNode curt = head;
        //
        //        while ( curt != null ) {
        //            if ( i == n )
        //                prev = prev == null ? head : prev.next;
        //            else
        //                i++;
        //            curt = curt.next;
        //        }
        //
        //        if ( i == n ) {
        //            if ( prev == null )
        //                return head.next;
        //            else
        //                removeNext(prev);
        //        }
        //
        //        return ret;
    }

    private static void removeNext(ListNode node) {
        if ( node.next != null )
            node.next = node.next.next;
    }

    public static ListNode create() {
        ListNode ret = new ListNode(0);
        ret.next = new ListNode(1);
//        ret.next.next = new ListNode(2);
//        ret.next.next.next = new ListNode(3);
        return ret;
    }

}
